package net.esj.basic.utils.algorithm;

import java.util.Arrays;
import java.util.Comparator;
import java.util.NoSuchElementException;

import net.esj.basic.core.engine.util.RandomUtils;

public class RoundTableAlgorithm extends AbstractAlgorithm {

	private static final int MAX_RATE = 10000;
	
	@Override
	void calc() {
		Arrays.sort(getItems(), new Comparator<AlgoEntity>() {

			@Override
			public int compare(AlgoEntity o1, AlgoEntity o2) {
				if(o1.getRate() >= o2.getRate()){
					return 1;
				}else{
					return -1;
				}
			}
			
		});
	}

	@Override
	public AlgoEntity pop() {
		int i = 0,sum = 0;
		int rnd = RandomUtils.get(MAX_RATE);
		for(;;){
			AlgoEntity ae = getItems()[i];
			if(ae==null)
				throw new NoSuchElementException();
			i++;
			sum += ae.getRate();
			if(ae.getRate()<rnd){
				continue;
			}else{
				return ae;
			}
		}
	}

}
